package media

import (
	"gitee.com/sdumeeting/sfu-server/global"
	"github.com/pion/webrtc/v2"
	"time"
)

var engine *WebRTCEngine

func init() {
	engine = NewWebRTCEngine()
}

type WebRTCPeer struct {
	id int

	// 表示 WebRTC 连接
	// 它会与实现相应协议的另一个端点建立 p2p 通信
	PC *webrtc.PeerConnection

	// 视频轨道
	VideoTrack *webrtc.Track
	// 音频轨道
	AudioTrack *webrtc.Track

	stop chan int

	// picture loss indication 关键帧丢包重传
	pli chan int
}

func NewWebRTCPeer(id int) *WebRTCPeer {
	return &WebRTCPeer{
		id:   id,
		stop: make(chan int),
		pli:  make(chan int),
	}
}

func (p *WebRTCPeer) Stop() {
	close(p.stop)
	close(p.pli)
}

// AnswerPublisher 响应发布者
func (p *WebRTCPeer) AnswerPublisher(offer webrtc.SessionDescription) (
	answer webrtc.SessionDescription, err error) {

	// 创建媒体流接收器，并获取相应的 SDP 信息
	return engine.CreateMediaStreamReceiver(offer, &p.PC, &p.VideoTrack, &p.AudioTrack, p.stop, p.pli)
}

// AnswerSubscriber 响应订阅者
func (p *WebRTCPeer) AnswerSubscriber(offer webrtc.SessionDescription,
	addVideoTrack, addAudioTrack **webrtc.Track) (answer webrtc.SessionDescription, err error) {

	// 创建媒体流发送器，并获取相应的 SDP 信息
	return engine.CreateMediaStreamSender(offer, &p.PC, addVideoTrack, addAudioTrack)
}

func (p *WebRTCPeer) SendPLI() {
	go func() {
		defer func() {
			if r := recover(); r != nil {
				global.Logger.Error(r)
			}
		}()

		ticker := time.NewTicker(time.Second)
		i := 0
		for {
			select {
			case <-ticker.C:
				p.pli <- 1
				if i > 3 {
					return
				}
				i++
			case <-p.stop:
				return
			}
		}
	}()
}
